<template>
  <MyModal ref="myModal" title="订单详情" :top="35">
    <template #content>
      <div class="row">
        <div class="left">
          <div class="image">
            <img :src="info?.filmImg" style="width: 150px" />
          </div>
          <div class="c-content">
            <div class="left-item marginTop">
              <span class="left-key">城市:</span>
              <span class="left-value">{{ info?.city }}</span>
            </div>
            <div class="left-item marginTop">
              <span class="left-key">订单号:</span>
              <span class="left-value">{{ info?.orderNumber }}</span>
            </div>
            <div class="left-item marginTop">
              <span class="left-key">影院名称:</span>
              <span class="left-value">{{ info?.cinemaName }}</span>
            </div>
            <div class="left-item marginTop">
              <span class="left-key">影院地址:</span>
              <span class="left-value">
                <a-tooltip placement="top">
                  <template #title>
                    {{ info.cinemaAddress || '-' }}
                  </template>
                  <span class="hiddenText">{{ info.cinemaAddress || '-' }}</span>
                </a-tooltip>
              </span>
            </div>
            <div class="left-item marginTop">
              <span class="left-key">电影名称:</span>
              <span class="left-value">{{ info?.filmName }}</span>
            </div>
            <div class="left-item marginTop">
              <span class="left-key">开场时间:</span>
              <span class="left-value">
                <a>{{ timeFormat(info?.showTime) }}</a>
              </span>
            </div>
            <div class="left-item marginTop seat">
              <span class="left-key">座位信息:</span>
              <div class="seat-value">
                <!-- <a-tag color="blue" v-for="item in info?.seatList" :key="item.id">
                                    {{ item.seatName }}
                                </a-tag> -->

                <span
                  class="seat-item"
                  v-if="seatList"
                  v-for="item in seatList"
                  :key="item"
                  @dblclick="handleSeatClick(item)"
                >
                  <span v-if="!item.flag">{{ item.seatName }}</span>
                  <a-input
                    v-else
                    style="width: 100px"
                    type="text"
                    @blur="handleSeatBlur(item)"
                    v-model:value="item.seatName"
                  />
                </span>
                <span style="color: #999; margin-left: 8px">(双击座位可修改)</span>
              </div>
            </div>
          </div>
        </div>
        <div class="right">
          <div class="right-item marginTop">
            <span class="right-key">影厅:</span>
            <span class="right-value">{{ info?.showName }}</span>
          </div>
          <div class="right-item marginTop">
            <span class="right-key">原价:</span>
            <span class="right-value">￥{{ (info?.originalPrice / 100).toFixed(2) }}</span>
          </div>
          <div class="right-item marginTop">
            <span class="right-key">出票价:</span>
            <span class="right-value">￥{{ (info?.finalPrice / 100).toFixed(2) }}</span>
          </div>
          <div class="right-item marginTop">
            <span class="right-key">订单结算:</span>
            <span class="right-value">￥{{ (info?.orderFinalPrice / 100).toFixed(2) }}</span>
          </div>
          <div class="right-item marginTop">
            <span class="right-key">票数:</span>
            <span class="right-value">{{ info?.seatCount }}</span>
          </div>
        </div>
      </div>
      <!-- action="http://crm.liangpiaovip.com/platform/wechatReply/uploadToAliOss" -->
      <!-- <div class="right">
       
      </div> -->

      <div class="price-ipt-container">
        <div class="title">出票价</div>
        <a-input
          v-model:value="finalPrice"
          style="width: 130px"
          placeholder="请输入出票价"
          suffix="元"
        ></a-input>
      </div>

      <div class="upload-load-container">
        <!-- <div class="left"> -->
        <a-upload-dragger
          action="http://crm.liangpiaovip.com/platform/wechatReply/uploadToAliOss"
          :beforeUpload="handleBeforeUpload"
          :customRequest="customRequest"
          list-type="text"
          :file-list="fileLists"
          v-model:file-list="fileLists"
          @change="handleChange"
          @remove="handleRemove"
          :max-count="4"
        >
          <p class="ant-upload-drag-icon">
            <!-- <inbox-outlined></inbox-outlined> -->
            <img src="@/assets/vote.png" style="width: 40px" />
          </p>
          <p class="ant-upload-text">请上传你的取票码</p>
          <!-- <p class="ant-upload-hint">
            请上传正确的取票码图片，如有虚假，后果自负，面临严重问题，将取消订单，并扣除相应余额。
          </p> -->
        </a-upload-dragger>
        <!-- </div> -->
      </div>

      <div class="upload-load-Text">
        <div class="upload-load-Text-item" v-for="(item, index) in ImageCodeList" :key="index">
          <div class="img">
            <a-image :height="150" :src="item.ticket" />
          </div>
          <div class="ticketCode">
            <div class="title">取票码：</div>
            <div class="ipt">
              <a-input style="width: 130px" v-model:value="item.ticketCode"></a-input>
            </div>
          </div>
          <div class="validateCode">
            <div class="title">验证码：</div>
            <div class="ipt">
              <a-input style="width: 130px" v-model:value="item.validateCode"></a-input>
            </div>
          </div>
        </div>
      </div>

      <div class="modal-btn">
        <div></div>
        <div class="right">
          <a-button type="default" @click="onCancel">取消</a-button>
          <div style="width: 10px"></div>
          <a-button type="primary" @click="onConfirmBtn">确定</a-button>
        </div>
      </div>
    </template>
  </MyModal>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import { timeFormat } from '@/hooks/util'
import * as orderApi from '@/api/order'
import Modal from '@/components/Modal/index.vue'
import jsQR from 'jsqr'
import { scanQrCode } from '../components/qrcode.js'
const myModal = ref()
const info = ref({})
const id = ref('')

const ImageCodeList = ref([])

const finalPrice = ref('')

const seatList = ref([])

let robotId = ref<string>('')
const showModal = (record: any) => {
  myModal.value?.showModal()
  // id.value = record.id
  info.value = record
  seatList.value = record.seatNos.split(',').map(item => {
    return {
      flag: false,
      seatName: item,
    }
  })
}

const SeatModalRef = ref(null)

const SeatByconfirm = () => {}

const fileLists = ref<Array<any>>([])
const handleBeforeUpload = (file: any, fileList: any) => {
  // console.log('file=', file)
  // console.log('fileList=', fileList)
  //   fileLists.value = fileList
  return true
}

const handleSeatClick = item => {
  console.log(item, 'item')
  item.flag = true
}
const handleSeatBlur = item => {
  item.flag = false
}
// 修改票吗
const updatedSeta = () => {
  SeatModalRef.value.setVisible(true)
}

const decodeQRCode = file => {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.onload = () => {
      const canvas = document.createElement('canvas')
      const context = canvas.getContext('2d')
      canvas.width = img.width
      canvas.height = img.height
      context.drawImage(img, 0, 0, img.width, img.height)

      const imageData = context.getImageData(0, 0, canvas.width, canvas.height)
      const code = jsQR(imageData.data, imageData.width, imageData.height)

      if (code) {
        resolve(code.data)
      } else {
        resolve(null)
      }
    }
    img.onerror = () => reject(new Error('图片加载失败'))
    img.src = URL.createObjectURL(file)
  })
}

const customRequest = (option: any) => {
  const { onSuccess, onError, file, action, data = {} } = option

  // 自定义参数名
  const formData = new FormData()
  formData.append('file', file)
  formData.append('type', '3')

  // 添加其他自定义数据
  // Object.keys(data).forEach(key => {
  //   formData.append(key, data[key])
  // })

  fetch(action, {
    headers: {
      'User-Token': localStorage.getItem('token') as any,
    },
    method: 'POST',
    body: formData,
  })
    .then(response => response.json())
    .then(async result => {
      onSuccess(result, file)
      // console.log('result=', result)
      // console.log('file=', file)
      console.log(result, file, 'result, file')

      console.log(fileLists.value, 'fileListsfileListsfileLists')

      try {
        const resultCode = await decodeQRCode(file)
        if (resultCode) {
          console.log(resultCode, 'resultresultresultresult')
          if (resultCode.includes('|')) {
            // 找到第一个 | 的位置
            const firstPipeIndex = resultCode.indexOf('|')

            // 分割字符串
            let ticketCode = resultCode.substring(0, firstPipeIndex)
            let validateCode = resultCode.substring(firstPipeIndex + 1)

            console.log('分割结果:', { ticketCode, validateCode })

            if (validateCode.includes('|')) {
              validateCode = validateCode.substring(0, validateCode.indexOf('|'))
            }

            ImageCodeList?.value.push({
              ticket: result.data,
              ticketCode: ticketCode,
              validateCode: validateCode,
            })
          } else {
          }
        } else {
          ImageCodeList?.value.push({
            ticket: result.data,
            ticketCode: '',
            validateCode: '',
          })
        }
      } catch (err) {}
    })
    .catch(error => {
      console.log(error, 'error')

      onError(error)
    })
}

const handleChange = (info: any) => {
  console.log('info=', info)

  // console.log('info=', info)
  let resFileList = [...info.fileList]
  resFileList = resFileList.map(file => {
    if (file.response) {
      file.url = file.response.data
    }
    return file
  })
  //   fileLists.value = resFileList
}
const handleRemove = file => {
  let url = file.response.data
  ImageCodeList.value = ImageCodeList.value.filter(item => item.ticket !== url)
}

//弹窗取消
const onCancel = () => {
  myModal.value?.cancelModal()
}
//弹窗确定
const onConfirmBtn = async () => {
  if (ImageCodeList.value.length < 1) {
    message.error('请上传取票码！')
    return
  }
  if (!finalPrice.value && Number(finalPrice.value) < 0) {
    message.error('请输入正确的出票金额！')
    return
  }

  const params = {
    finalPrice: finalPrice.value * 100,
    orderId: info.value.id,
    // seatInfos: seatInfos,
    tickets: ImageCodeList.value,
  }
  const seatInfos = seatList.value.map(item => {
    return {
      seatName: item.seatName,
    }
  })
  const seatInfosStr = seatList.value.map(item => item.seatName).join(',')
  console.log(seatInfosStr, info.value.seatNos, 'info.value.seatNosinfo.value.seatNos')

  if (info.value.seatNos != seatInfosStr) {
    params.seatInfos = seatInfos
  }

  try {
    const result = await orderApi.submitFilmOrderByOwn(params)

    if (result.state == 200) {
      message.success('提交成功~')
      myModal.value?.cancelModal()
      emit('refresh')
    } else {
      message.error(result.message)
    }
  } catch (error) {}
}

const shwoImgge = (row: any) => {
  emit('ImagePreview', [row])
}
const emit = defineEmits<{
  refresh: []
  ImagePreview: []
}>()

defineExpose({
  showModal,
})

interface formState {
  code: string
}
const formState = ref<formState>({
  code: '',
})

const handleSubmit = async () => {
  let params = {
    code: formState.value.code,
    robotId: robotId.value,
  }
  try {
    // const { state, message: msg } = await accountApi.openCard(params)
    // if (state === 200) {
    message.success('激活成功')
    myModal.value?.cancelModal()
    emit('refresh')
    // } else {
    //     message.error(msg)
    // }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
</script>
<style lang="less">
.ant-upload-list .ant-upload-list-picture {
  opacity: 0 !important;
}
.row {
  display: flex;
  justify-content: space-between;
  font-size: 16px;

  .left {
    display: flex;

    .c-content {
      margin-left: 20px;
      font-size: 12px;
      .left-item {
        display: flex;
        // align-items: center;
      }

      .left-value {
        margin-left: 10px;
        color: #15181d;
        font-size: 16px;
      }
      .hiddenText {
        display: inline-block;
        width: 300px;
        overflow: hidden;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }

      .left-key {
        color: #858a99;
        font-size: 16px;
      }
      .seat-value {
        margin-left: 6px;
      }
      .seat-item {
        // display: flex;
        // align-items: center;
        cursor: pointer;
      }

      .seat-item:nth-child(n + 2) {
        margin-left: 12px;
      }

      .marginTop {
        margin-top: 10px;
      }
      .seat {
        display: flex;
        font-size: 16px;
      }
    }
  }

  .right {
    font-size: 14px;

    .right-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 10px;

      .right-value {
        margin-left: 10px;
        color: #15181d;
        font-size: 16px;
      }

      .right-key {
        color: #858a99;
        font-size: 16px;
      }
    }

    .marginTop {
      margin-top: 10px;
    }
  }
}
.price-ipt-container {
  width: 100%;
  padding: 15px;
  margin-top: 20px;
  display: flex;
  align-items: center;
  .title{
    margin-right: 15px;
  }
}

.upload-load-container {
  margin-top: 20px;
  padding: 15px;
  width: 100%;
  // display: flex;
  // align-items: center;
  // justify-content: space-between;

  .left {
    display: flex;
    align-items: center;
  }
  .right {
    display: flex;
    align-items: center;
    .item {
      display: flex;
      align-items: center;
      .title {
        margin-right: 10px;
        color: #858a99;
      }
    }
    .item:nth-child(n + 2) {
      margin-left: 10px;
    }
  }
}
.modal-btn {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .right {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
.upload-load-Text {
  padding: 20px;
  box-sizing: border-box;
  margin-top: 20px;
  display: flex;
  align-items: center;
  width: 100%;
  .upload-load-Text-item {
    .img {
      margin-top: 10px;
    }
    .ticketCode {
      margin-top: 10px;
    }
    .validateCode {
      margin-top: 10px;
    }
    // flex: 1;
    width: 25%;
  }
  .upload-load-Text-item:nth-child(n + 2) {
    // margin-left: 15px;
  }
}

.vote-box {
  margin-top: 60px;
  display: flex;
  align-items: center;

  .vote-item {
    display: flex;
    flex-direction: column;

    .content {
      margin-top: 20px;
      display: flex;
      flex-direction: column;
      flex: 1;
    }

    // align-items: center;
  }

  .vote-item:nth-child(n + 2) {
    margin-left: 30px;
  }
}
</style>
